module agame
import StdEnv, japi

/* Another animation, where the sprite is
static, and the background moves.
****************/

:: Stt= { fr::!Framer, sel::!Int, key:: !Device,
          bp::!P, speed :: !Int, sph:: !Int, 
          dx::!Int, cv::!Canvas, img :: !{#Int},
          w::!Int, h::!Int, ky::!Int, bal:: !Int}

:: Thing :== .(.Int -> [.Drawable])	

Start world
  # (js, world) = begin_japi world
    (sky, js) = jloadimage "blusky.jpg" js
    (w, h, js) = imagesize sky js 
    (frm, js) = jnewFrame  (WH (w+6) (h+30)) "Flying bird" js
    (cvs, js) = jnewCanvas (XYWH 6 30 w h) frm  js
    (img_a,js) = load_images js
    (sprite_h, js)= imageheight img_a.[0] js
    (frm, js) = jshow frm js
    (balloon, js)= jloadimage "balloon.gif" js
    (kb, cvs) = jkeyboard cvs
   
    (cvs, js)= jsetfocus cvs js
    s= { fr= frm, sel= 0, dx= 0, cv= cvs, key= kb,
         bp= (40, 10), speed= 40, sph= sprite_h,
         w=w, h=h, ky= sky, img= img_a, bal= balloon}
    (p1, js)= randpos w h js
    (p2, js)= randpos w h js
    js = loop s p1 p2 js 
  = end_japi js world

loop :: !Stt !P !P !JapiState -> *JapiState
loop s p1 p2 js
	| s.dx < ~s.w
		# (p, js)= randpos s.w s.h js
		= loop {s & dx= 0} p2 p js
	# (x,js) = jsleep 150 js
	# (na,js) = jgetaction x js
	| na== act s.key
	    # sl = (s.sel+1) rem (size s.img)
	    # s= dXdY s.h s.sph s
  		# cvs = jdraw (Img (s.dx,0) s.ky) s.cv
		# cvs = jdraw (Img (s.dx+s.w, 0) s.ky) cvs
		# cvs = jdraw (Img s.bp s.img.[s.sel]) cvs
		# cvs = draw [Img (p1+(s.dx,0)) s.bal] cvs 
		# cvs = draw [Img (p2+(s.dx+s.w, 0)) s.bal] cvs 
		# js= jsync js
		# sl = (s.sel+1) rem (size s.img)
    	= loop {s& sel=sl, dx= s.dx-s.speed, cv= cvs} p1 p2 js
	| na==(act s.fr)
		# js= jdispose s.cv js
		= jquit js
	# cvs = jdraw (Img (s.dx,0) s.ky) s.cv
	# cvs = jdraw (Img (s.dx+s.w, 0) s.ky) cvs
	# cvs = jdraw (Img s.bp s.img.[s.sel]) cvs
	# cvs = draw [Img (p1+(s.dx,0)) s.bal] cvs 
	# cvs = draw [Img (p2+(s.dx+s.w, 0)) s.bal] cvs 
	# js= jsync js
	# sl = (s.sel+1) rem (size s.img)
    = loop {s& sel=sl, dx= s.dx-s.speed, cv= cvs} p1 p2 js

load_images :: !JS -> (!{#Int},!*JS)
load_images js
	#	(b1,js) = jloadimage "helico1.gif" js
		(b2,js) = jloadimage "helico2.gif" js
	=   ({b1, b2},js)

randpos w h js
	#	(x, js)= jrandom (w-100) js
		(y, js)= jrandom h js
	= ((x, y), js)
	   
dXdY h dh s
  # kc= jkeycode s.key
  | kc == 37 = {s& speed=  max 10 (s.speed - 10)}
  | kc == 39 = {s& speed= min (s.speed + 10) 60 }
  # (x, y)= s.bp
  | kc == 38 = {s& bp= (x, max 10 (y-40))}
  | kc == 40 = {s& bp= (x, min (h-dh) (y+40))}
  | otherwise= s
 